/*
 * @Author: 王明明834578987 10266004+wang-mingming-834578987@user.noreply.gitee.com
 * @Date: 2024-04-26 14:58:29
 * @LastEditors: mcc 550539422@qq.com
 * @LastEditTime: 2024-08-12 15:52:27
 * @FilePath: \ft-apply\src\api\http.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios, { AxiosResponse } from "axios";
import { Result } from "../assets/type/common";
import NProgress from "nprogress";
import { showToast } from "vant";
import { localUserinfo } from "../assets/js/common";

NProgress.configure({ showSpinner: false });

// 测试环境和生产环境互换
//const { MODE } = import.meta.env;
//let env = MODE === "production" ? "newKejian-pro" : "newKejian-test";
const request = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
});

// http request拦截器
request.interceptors.request.use(
  (config) => {
    const userInfo = localUserinfo();
    let token = userInfo != null ? userInfo.token : "";
    if (token) {
      config.headers.authorization = token; //请求头加上token
      config.headers.token = token;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
request.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    NProgress.start();
    //拦截响应，做统一处理
    if (response?.data.code) {
      switch (response?.data.code) {
        case "10001": //注意字符串不是数字
          // 使用 Promise 包装 showToast
          showToast(response.data.msg);
          break;
      }
    }
    NProgress.done();
    return response;
  },
  //接口错误状态处理，也就是说无响应时的处理
  (error) => {
    NProgress.done();
    return Promise.reject(error?.response?.status); //接口返回的错误信息
  }
);

export function get(url: string, params: any) {
  return new Promise((resolve, reject) => {
    request
      .get(url, { params: params })
      .then((res: AxiosResponse<Result>) => {
        resolve(res.data as unknown);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export function post(
  url: string,
  params: any,
  config: any = { "Content-Type": "application/json;charset=utf-8" }
) {
  return new Promise((resolve, reject) => {
    request
      .post(url, params, config)
      .then((res: AxiosResponse<Result>) => {
        resolve(res.data as unknown);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
